package org.liaohailong.library.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

/**
 * create by liaohailong
 * time 2022/8/23 18:07
 * desc:
 */
public abstract class BaseDialogFragment extends DialogFragment {

    public void show(@NonNull FragmentActivity activity) {
        FragmentManager fm = activity.getSupportFragmentManager();
        show(fm, getClass().getCanonicalName());
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Dialog dialog = new Dialog(getContext(), getThemeResId());
        dialog.setContentView(getLayoutId());
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);

        Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams attributes = window.getAttributes();
            attributes.width = getWindowWidth();
            attributes.height = getWindowHeight();
            attributes.gravity = getGravity();
            window.setAttributes(attributes);
        }
        return dialog;
    }

    @Override
    public void onStart() {
        super.onStart();

        Dialog dialog = getDialog();
        if (dialog == null) return;
        Window window = dialog.getWindow();
        if (window == null) return;
        View decorView = window.getDecorView();
        if (decorView == null) return;

        initView(decorView);
    }

    /**
     * @return dialog主题资源id
     */
    protected abstract int getThemeResId();

    /**
     * @return dialog内容布局资源id
     */
    @LayoutRes
    protected abstract int getLayoutId();

    /**
     * @return dialog所属window的宽度
     */
    protected int getWindowWidth() {
        return WindowManager.LayoutParams.MATCH_PARENT;
    }

    /**
     * @return dialog所属window的高度
     */
    protected int getWindowHeight() {
        return WindowManager.LayoutParams.WRAP_CONTENT;
    }

    /**
     * @return dialog在window中摆放的位置
     */
    protected abstract int getGravity();

    /**
     * @param view 初始化view，在onStart函数中回调
     */
    protected abstract void initView(@NonNull View view);
}
